<!-- DateTimePicker -->
<template>
  <div class="time-picker">
    <el-date-picker v-model="values" :type="type" :placeholder="placeholder" :value-format="valueFormat" :format="format"
                    :prefix-icon="prefixIcon" :picker-options="needPickerOptions ? pickerOptions: {}" :clearable="clearable"
                    @change="handleChange" :default-time="defaultTime">
    </el-date-picker>
  </div>
</template>

<script>
import { DateTimeFormat } from '@/utils'
export default {
  name: 'TimePicker',
  data () {
    return {
      values: '',
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      }
    }
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'date'
    },
    placeholder: {
      type: String,
      default: '请选择日期时间'
    },
    valueFormat: {
      type: String,
      default: ''
    },
    format: {
      type: String,
      default: ''
    },
    prefixIcon: {
      type: String,
      default: 'el-icon-time'
    },
    defaultTime: {
      type: String,
      default: ''
    },
    clearable: {
      type: Boolean,
      default: true
    },
    needPickerOptions: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    value: function (val) {
      this.values = val
    }
  },
  mounted () {
    this.values = this.value
  },
  methods: {
    handleChange (value) {
      let dateTime = ''
      if (value && value instanceof Date) {
        let timeStr = this.valueFormat || 'yyyy-MM-dd hh:mm:ss'
        dateTime = DateTimeFormat(value, timeStr)
      } else {
        dateTime = value
      }
      this.$emit('input', dateTime)
    }
  }
}

</script>
